// import 'package:animated_digit/animated_digit.dart';

import 'package:flutter/material.dart';
import 'package:yl_kit/extension/yl_extension.dart';

class AnimText extends StatefulWidget {
  final num number;
  final int duration;
  final Color? fontColor;
  final double? fontSize;
  final FontWeight? fontWeight;
  final String? fontFamily;
  final List<InlineSpan>? children;
  final TextStyle? textStyle;

  final int digits;
  const AnimText({
    super.key,
    required this.number,
    this.duration = 500,
    this.digits = 2,
    this.fontColor,
    this.fontSize,
    this.fontWeight,
    this.fontFamily,
    this.children,
    this.textStyle,
  });

  @override
  _AnimTextState createState() => _AnimTextState();
}

class _AnimTextState extends State<AnimText>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;

  late Animation<double> cover;
  late Animation animation;

  double begin = 0.0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    controller = AnimationController(
        vsync: this, duration: Duration(milliseconds: widget.duration));
    cover = CurvedAnimation(parent: controller, curve: Curves.linear);
    animation = Tween<num>(begin: begin, end: widget.number).animate(cover);

    controller.forward();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    controller.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant AnimText oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);

    if (oldWidget.number != widget.number) {
      cover = CurvedAnimation(parent: controller, curve: Curves.linear);
      animation = Tween<num>(begin: oldWidget.number, end: widget.number)
          .animate(cover);
      controller.reset();
      controller.forward();
    }
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: controller,
      builder: (_, child) {
        return Text.rich(
          TextSpan(children: [
            TextSpan(
              text: '${animation.value}'.keepShortDigits(widget.digits),
            ),
            ...widget.children ?? []
          ]),
          style: widget.textStyle ??
              TextStyle(
                  fontFamily: widget.fontFamily,
                  fontSize: widget.fontSize ?? 14,
                  color: widget.fontColor ?? Colors.black,
                  fontWeight: widget.fontWeight),
        );
      },
    );
  }
}
